# f = open("test.txt", "r")
# f = open(r"C:\Work\Pyhon\helloworld\test.txt", "r")
# try:
#     f = open(r"test.txt", encoding="utf-8")
#     text = f.read()
#     print(text)
# finally:
#     f.close()

# with 上下文管理器, 可以自动关闭文件, 不需要手动关闭文件
with open(r"test.txt", encoding="utf-8") as f:
    text = f.read(1)
    print(f.tell()) # 指针位置
    f.seek(0) # 指针位置
    text = f.read()
    print(text)

print(f.closed)
print(f.mode)
print(f.name)

# 文件复制
with open(r"test.txt", encoding="utf-8") as f:
    with open(r"test_copy.txt", "w", encoding="utf-8") as f2:
        text = f.read()
        f2.write(text)  # 写入文件, 指针位置会移动到文件末尾, 所以需要手动移动指针位置, 否则会覆盖原来的内容 


# 大文件复制
with open(r"test.txt", encoding="utf-8") as f:
    with open(r"test_copy.txt", "w", encoding="utf-8") as f2:
        while True:
            text = f.read(1024) # 每次读取1024个字节
            if not text: # 如果读取到的内容为空, 则表示文件已经读取完毕, 退出循环
                break
            f2.write(text) # 写入文件, 指针位置会移动到文件末尾, 所以需要手动移动指针位置, 否则会覆盖原来的内容
        
# 一次读一行
with open(r"test.txt", encoding="utf-8") as f:
    with open(r"test_copy.txt", "w", encoding="utf-8") as f2:
        while True:
            text = f.readline() # 每次读取一行, 指针位置会移动到下一行的开头, 所以不需要手动移动指针位置, 会自动移动指针位置, 不会覆盖原来的内容
            if not text: # 如果读取到的内容为空, 则表示文件已经读取完毕, 退出循环
                break
            f2.write(text) # 写入文件, 指针位置会移动到文件末尾, 所以需要手动移动指针位置, 否则会覆盖原来的内容
# 一次读多行
with open(r"test.txt", encoding="utf-8") as f:
    with open(r"test_copy.txt", "w", encoding="utf-8") as f2:
        while True:
            text = f.readlines() # 每次读取多行, 指针位置会移动到下一行的开头, 所以不需要手动移动指针位置, 会自动移动指针位置, 不会覆盖原来的内容
            if not text: # 如果读取到的内容为空, 则表示文件已经读取完毕, 退出循环
                break   
            f2.writelines(text) # 写入文件, 指针位置会移动到文件末尾, 所以需要手动移动指针位置, 否则会覆盖原来的内容